/****************************************************
 *javascript KXBASE 前端开发框架
 *@desc 提供常用的表单验证、数据格式转换 权限验证和控制组件css的功能等等
 *      KXBASE命名空间下定义了许多常用函数
 *@data 2012年9月11日13:11:22
*******************************************************/
/**
 * T模板
 */
(function(){function c(a){this.t=a}function l(a,b){for(var e=b.split(".");e.length;){if(!(e[0]in a))return!1;a=a[e.shift()]}return a}function d(a,b){return a.replace(h,function(e,a,i,f,c,h,k,m){var f=l(b,f),j="",g;if(!f)return"!"==i?d(c,b):k?d(m,b):"";if(!i)return d(h,b);if("@"==i){e=b._key;a=b._val;for(g in f)f.hasOwnProperty(g)&&(b._key=g,b._val=f[g],j+=d(c,b));b._key=e;b._val=a;return j}}).replace(k,function(a,c,d){return(a=l(b,d))||0===a?"%"==c?(new Option(a)).innerHTML.replace(/"/g,"&quot;"):
a:""})}var h=/\{\{(([@!]?)(.+?))\}\}(([\s\S]+?)(\{\{:\1\}\}([\s\S]+?))?)\{\{\/\1\}\}/g,k=/\{\{([=%])(.+?)\}\}/g;c.prototype.render=function(a){return d(this.t,a)};window.t=c})();
/**
 * end
 */



/**
 * 判断是否存在KXBASE命名空间 不存在就创建一个
 */
if(typeof KXBASE == "undefined" ||!KXBASE) {
    var KXBASE = {};
}


/**
 * 创建一个命名空间 KXBASE
 * @namespace KXBASE
 */
KXBASE.namespace = function() {
    var a=arguments, o=null, i, j, d;
    for (i=0; i<a.length; i=i+1) {
        d=a[i].split(".");
        o=KXBASE;

        for (j=(d[0] == "KXBASE") ? 1 : 0; j<d.length; j=j+1) {
            o[d[j]]=o[d[j]] || {};
            o=o[d[j]];
        }
    }
    return o;
};



/**
 * 对方法的操作，解决内存泄露问题
 * @namespace KXBASE.fn
 */
KXBASE.fn=KXBASE.fn ||{};



/**
 * 这是一个空函数，用于需要排除函数作用域链干扰的情况.
 * @return {Function} 一个空函数
 */
KXBASE.fn.blank = function () {};


var $b=KXBASE.fn;

/*********************************************************
 * 数据格式验证函数定义区
***********************************************************/
KXBASE.fn.isEmpty=function(something){
return (something=="undefined"||something==null||something==""||something==false);
}

KXBASE.fn.isNotEmpty=function(something){
return ((something!=null&&something!="undefined"&&something!="")||something==true);
}

/**
*删除最后一个字符
*/
function deleteLastChar(str,c){
    var reg=new RegExp(c+"([^"+c+"]*?)$");
    return str.replace(reg,function(w){if(w.length>1){return w.substring(1);}else{return "";}});
}

var interval;//计时器


//常用表单验证封装
String.prototype.trim=function(){return this.replace(/(^\s*)|(\s*$)/g, "");}


var g = function (id) {
    return "string" == typeof id ? document.getElementById(id) : id;
};
//摇摆摇摆摇摆起来
jQuery.fn.shake = function(intShakes /*Amount of shakes*/, intDistance /*Shake distance*/, intDuration /*Time duration*/) {
    this.each(function() {
        var jqNode = $(this);
        jqNode.css({position: 'relative'});
        for (var x=1; x<=intShakes; x++) {
            jqNode.animate({ left: (intDistance * -1) },(((intDuration / intShakes) / 4)))
            .animate({ left: intDistance },((intDuration/intShakes)/2))
            .animate({ left: 0 },(((intDuration/intShakes)/4)));
        }
    });
    return this;
}

//检查form表单中的input textarea select
var checkInput=function(optform){
    var error=true;
    $("input,textarea,select",optform).each(function(){
        if(!error){
            return error;
        }
        var input=$(this);
        if(typeof(input.attr("check"))!="undefined"){
            var flag = checktype(input);
            if (!flag) {
                input.css("border","dashed 1px red").css("background","#D3E6B6");
                input.shake(2,10,400);
                input.focus();
                error=false;
                return;
            }
            error=true;
            input.css("border","solid 1px #7F9DB9").css("background","#FFFFFF");
        }
    });
    return error;

}

//检查给定一个input textarea select的值
function checktype(input) {
    var type=input.attr("check"),
     value=input.val(),
     mytips=input.attr("tips"),
      show=input.attr("show"),
      notNull=input.attr("notNull");
    if (show != null) {
            g(show).innerHTML = "";
    }
        //检测是否为空
            if (value == null || value == "") {
            //检查配置是否需要进行非空检测
                            if(notNull==null||notNull==true||notNull=="true"){
                                    if(mytips!=null){
                                        if (show == null) {
                                            alert(mytips);
                                        } else {
                                            g(show).innerHTML = mytips;
                                        }
                                    }
                            return false;
                            }else{
                            return true;
                            }
            }else{
                value=value.trim();
            }
    return checkTypes(type,value,mytips,show,notNull);

}
//检测数据类型
function checkTypes(type,value,mytips,show,notNull){
    //验证多个的时候
    var types=type.split("&");
    var checkFlag=true;
    var error=1;
    var success=2;
    var canNotCheck=3;
    for(var i=0;i<types.length;i++){
        var type=types[i];
        var checkResult=checkSelf(type,value,mytips,show,notNull);
        if(checkResult!=canNotCheck){//判断能否处理 如果处理了 成功了继续下一个type 失败了则直接整个结束
            if(checkResult==success){
                continue;
            }else{
                checkFlag=false;
                break;
            }
        }
        
        //如果上面不能处理 则进入比较处理
        checkResult=checkCompare(type,value,mytips,show,notNull);
        if(checkResult!=canNotCheck){//判断能否处理 如果处理了 成功了继续下一个type 失败了则直接整个结束
            if(checkResult==success){
                continue;
            }else{
                checkFlag=false;
                break;
            }
        }
        
        
    }
    return checkFlag;
}

//检测比较
function checkCompare(type,value,mytips,show,notNull){
    var error=1;
    var success=2;
    var canNotCheck=3;
    var selfValue=getRealTypeValue(value);
    var compareValue=getCompareValue(type);
    if(type.indexOf(">=")!=-1){
        if(selfValue>=compareValue){
            return success;
        }
        showMyTipsIfNeed(mytips,show);
        return error;
    }else if(type.indexOf("<=")!=-1){
        if(selfValue<=compareValue){
            return success;
        }
        showMyTipsIfNeed(mytips,show);
        return error;
    }else if(type.indexOf(">")!=-1){
        if(selfValue>compareValue){
            return success;
        }
        showMyTipsIfNeed(mytips,show);
        return error;
    }else if(type.indexOf("<")!=-1){
        if(selfValue<compareValue){
            return success;
        }
        showMyTipsIfNeed(mytips,show);
        return error;
    }else if(type.indexOf("!=")!=-1){
        if(selfValue!=compareValue){
            return success;
        }
        showMyTipsIfNeed(mytips,show);
        return error;
    }else if(type.indexOf("==")!=-1){
        if(selfValue==compareValue){
            return success;
        }
        showMyTipsIfNeed(mytips,show);
        return error;
    }

    return canNotCheck;
}
//得到正确类型的值
function getRealTypeValue(value){
    if(!isNaN(value)){
        return Number(value);
    }
    return value;
}
//得到需要比较的值
function getCompareValue(type){
    if(type.indexOf("#")!=-1){
        var cid=type.substring(type.indexOf("#"));
        return getRealTypeValue($(cid).val());
    }else{
        if(type.indexOf("=")!=-1){
            return getRealTypeValue(type.substring(2));
        }else{
            return getRealTypeValue(type.substring(1));
        }
    }
}
//显示提示信息
function showMyTipsIfNeed(mytips,show){
    if(mytips!=null){
                if (show == null) {
                    alert(mytips);
                } else {
                    g(show).innerHTML = mytips;
                }
                }
}
//验证规则map
var ruleMap=[
    {type:"double",method:function(value){return (!isNaN(value));}},//数字校验
    {type:"number",method:function(value){return (!isNaN(value));}},//数字校验
    {type:"pnumber",method:function(value){return (!isNaN(value)&&value*1>0);}},//验证正数
    {type:"int",method:function(value){return TestRgexp(/^-?[0-9]\d*$/, value);}},//整数校验
    {type:"pint",method:function(value){return TestRgexp(/^[0-9]*[1-9][0-9]*$/, value);}},//正整数校验
    {type:"email",method:function(value){return TestRgexp(/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/, value);}},//Email校验
    {type:"filepath",method:function(value){return TestRgexp(/^([a-zA-Z]){1}:(\\[^\/\\:\*\?\"<>]+)*(\\)?$/, value);}},//URL校验
    {type:"url",method:function(value){return TestRgexp(/^([a-zA-Z]){1}:(\\[^\/\\:\*\?\"<>]+)*(\\)?$/, value);}},//URL校验
    {type:"date",method:function(value){return TestRgexp(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/,value);}}//日期验证
];

//检测自身
function checkSelf(type,value,mytips,show,notNull){
    var error=1;
    var success=2;
    var canNotCheck=3;
    if(type=="string"){
        return success;
    }
    var process=false;
    for(var i=0;i<ruleMap.length;i++){
        if(type==ruleMap[i].type){
            process=true;
            var result=ruleMap[i].method.call(this,value);
            if (!result) {
                showMyTipsIfNeed(mytips,show);
                return error;
            }
        }
    }
    return process?success:canNotCheck;
 
    
}
//调用正则表达式验证
function TestRgexp(re, s) {
    return re.test(s);
}




/********************************************************
 * 定义一些常用的数学计算函数
 *******************************************************/
/**
 * 获得随机数 0~n之间的
 * @param {Object} n
 */
function getRandom(n){return Math.floor(Math.random()*n+1)}


/*********************************************************
 * 一些常用的页面效果使用的变量
***********************************************************/


var windowHeight=0;
var windowWidth=0;
var paddingwidth=0;
//处理固定头
var processScrollPanelWidth = function(){
    if ($(".breadcrumb").length > 0) {
        paddingwidth = 40;
    }
    windowHeight = $(window).height();
    windowWidth = $(window).width();
    KXBASE.fn.processScrollPanel();
    $("div.scrollPanel").css("width", windowWidth - paddingwidth);
    $("div.topDiv").css("width", windowWidth - paddingwidth);
    $("div.submitScrollAction").css("position", "absolute").css("z-index", "3").css("top", windowHeight - 35).css("left", (windowWidth - $(this).width()) / 2);
    $("a.submitScrollAction").each(function(){
        $(this).css("position", "absolute").css("z-index", "3").css("top", windowHeight - 35).css("left", (windowWidth - $(this).width()) / 2);
    });
    $("button.submitScrollAction").each(function(){
        $(this).css("position", "absolute").css("z-index", "3").css("top", windowHeight - 35).css("left", (windowWidth - $(this).width()) / 2);
    });
}

KXBASE.fn.processVariable=function(){
    $(window).resize(processScrollPanelWidth);
    $(window).load(processScrollPanelWidth);
}




/*********************************************************
 * 组件的处理函数 以下处理下拉列表 form表单 button等组件绑定的事件
***********************************************************/


/*********************************************************
 * 分页组件的处理函数 临时不用
***********************************************************/

KXBASE.pageNav = KXBASE.pageNav || {};
KXBASE.pageNav.fn = null;
KXBASE.pageNav.pre = "<<";
KXBASE.pageNav.next = ">>";
KXBASE.pageNav.nav = function (a, b) {
    if (1 >= b) {
        return this.pn = this.p = 1, this.pHtml2(1);
    }
    b < a && (a = b);
    var c = "";
    1 >= a ? a = 1 : (c += this.pHtml(a - 1, b, KXBASE.pageNav.pre), c += this.pHtml(1, b, "1"));
    this.p = a;
    this.pn = b;
    var d = 2, e = 9 > b ? b : 9;
    7 <= a && (c += "<li><a href=\"javascript:void(0)\" onclick=\"void(0)\">...</a></li>", d = a - 4, e = a + 4, e = b < e ? b : e);
    for (; d < a; d++) {
        c += this.pHtml(d, b);
    }
    c += this.pHtml2(a);
    for (d = a + 1; d <= e; d++) {
        c += this.pHtml(d, b);
    }
    e < b && (c = c + "<li><a href=\"javascript:void(0)\" onclick=\"void(0)\">...</a></li>" + this.pHtml(b, b));
    a < b && (c += this.pHtml(a + 1, b, KXBASE.pageNav.next));
    return c;
};
KXBASE.pageNav.pHtml = function (a, b, c) {
    return "<li> <a href=\"javascript:KXBASE.pageNav.go(" + a + "," + b + ");\">" + (c || a) + "</a></li>";
};
KXBASE.pageNav.pHtml2 = function (a) {
    return "<li class=\"active\"><a  href=\"javascript:void(0)\" onclick=\"void(0)\">" + a + "</a></li>"
};
KXBASE.pageNav.go = function (a, b) {
    document.getElementById("pagination").innerHTML = this.nav(a, b);
    null != this.fn && this.fn(this.p, this.pn);
};

/*********************************************************
 * 自定义弹出窗口的处理函数
***********************************************************/
KXBASE.fn.baseWin = function(windowIndex, title, url, width, height, btnSetting, operateBtnClick, closeBtnClick, extraBtnClick, modalHideHandler){
    var setting = eval(btnSetting);
    var winrandId = "commonModal" + (windowIndex == 0 ? getRandom(100) : windowIndex);
    var haveBtn = false;
    if (KXBASE.fn.isNotEmpty(setting.closeBtn) || KXBASE.fn.isNotEmpty(setting.extraBtn) || KXBASE.fn.isNotEmpty(setting.operateBtn)) {
        haveBtn = true;
    }
    var ml=0;
    if(width>=600){
    	ml=(0 - (width / 2)+200);
    }else{
    	ml=150;
    }
    
  /**
   * 创建窗口
   */
  var myWindow = '<div id="' + winrandId + '" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"  class="commonModal modal fade" style="margin-left: ' + ml + 'px;"><div class="modal-dialog"><div class="modal-content" style="width:' + width + 'px; "><div class="modal-header">'
  +
  '<button id="closeModalBtnSmall" type="button" class="close" ><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button><h4 class="modal-title" id="myModalLabel">' + title + '</h4></div><div class="modal-body noscroll" style="height:' + height + 'px;"><iframe id="commonActionIframe"   style="width:100%;height:' + (height -35) + 'px;border:0px;" frameborder="0" src=""></iframe></div><div class="modal-footer">';
  if (KXBASE.fn.isNotEmpty(setting.extraBtn)) {
      myWindow = myWindow + '<button  class="btn btn-primary pull-left" id="extraBtn">' + setting.extraBtn + '</button>';
  }
  if (KXBASE.fn.isNotEmpty(setting.operateBtn)) {
      myWindow = myWindow + '<button  class="btn btn-primary" id="operateBtn">' + setting.operateBtn + '</button>';
  }
  if (KXBASE.fn.isNotEmpty(setting.closeBtn)) {
      myWindow = myWindow + '<button  class="btn btn-default" id="closeModalBtn" >' + setting.closeBtn + '</button>';
  }
  myWindow = myWindow + '</div></div></div></div>';
    $("body").append(myWindow);
    $("#commonActionIframe").attr("src", url);
    /**
     * 绑定按钮事件
     */
    if (KXBASE.fn.isNotEmpty(setting.closeBtn)) {
        if (KXBASE.fn.isNotEmpty(closeBtnClick)) {
            $("#closeModalBtn").bind("click", function(){
                closeBtnClick();
                $("#" + winrandId).modal("hide");
            });
            $("#closeModalBtnSmall").bind("click", function(){
                closeBtnClick();
                $("#" + winrandId).modal("hide");
            });
        }
        else {
            $("#closeModalBtn").bind("click", function(){
                $("#" + winrandId).modal("hide");
            });
            $("#closeModalBtnSmall").bind("click", function(){
                $("#" + winrandId).modal("hide");
            });
        }
    }
    
    if (KXBASE.fn.isNotEmpty(operateBtnClick)) {
        $("#operateBtn").bind("click", function(){
        	$("#operateBtn").hide();
        	$("#extraBtn").hide();
            operateBtnClick();
        });
    }
    if (KXBASE.fn.isNotEmpty(extraBtnClick)) {
        $("#extraBtn").bind("click", function(){
            extraBtnClick();
        });
    }
    /**
     * 绑定窗口关闭事件
     */
    $("#" + winrandId).on("hidden.bs.modal", function(){
        $("#operateBtn").unbind("click");
        $("#extraBtn").unbind("click");
        $("#closeModalBtn").unbind("click");
        $("#closeModalBtnSmall").unbind("click");
        $("#" + winrandId).remove();
    });
    
    /**
     * 显示窗口
     */
    $("#" + winrandId).modal({
        backdrop: true,
        keyboard: false
    });
    
    if (KXBASE.fn.isNotEmpty(modalHideHandler)) {
    $("#" + winrandId).on("hide", function(){
        return modalHideHandler();
    });
}
    
    

}

/**
 * 给定窗口的Index 关闭它
 * @param {Object} windowIndex
 */
KXBASE.fn.closeByIndex=function(windowIndex){
    $("#commonModal"+windowIndex).modal("hide");
}
/*********************************************************
 * 自定义弹出消息窗口的处理函数
***********************************************************/
KXBASE.fn.alert = function(msg,sec,width){
    if(KXBASE.fn.isEmpty(width)||KXBASE.fn.isEmpty(height)){
        width=560;
    }
    clearTimeout(interval);
    var confirmWindow ='<div id="alertModal" class="alertModal modal hide fade in" style="z-index:5000;width:' + width + 'px; margin-left: ' + (0 - width / 2) + 'px;"><div class="modal-body"><p><img id="alertImg"  src="assets/img/info.png"  class="pull-left" /><span id="alertModalMsg" class="confirmMsg pull-right">' + msg + '</span></p></div></div>';
    $("body").append(confirmWindow);
    
    $("#alertModal").modal({
        backdrop:true,
        keyboard:false
    });
    
    if(sec>0){
        interval = setInterval(closeAlert, sec); 
    }
    
    
    
    
};

var closeAlert=function(){
    clearTimeout(interval);
    $("#alertModal").modal("hide");
};
/*********************************************************
 * 自定义弹出确认窗口的处理函数
***********************************************************/
/**
 * 自定义弹出确认窗口的处理函数
 * @param {Object} title
 * @param {Object} msg
 * @param {Object} width
 * @param {Object} height
 * @param {Object} btnSetting json格式{mode:'ync',yesBtn:'是',noBtn:'否',cancelBtn:'取消'}
 * @param {Object} yesClick
 * @param {Object} noClick
 */
KXBASE.fn.confirm = function(title, msg, width, height, btnSetting, yesClick, noClick){
    var setting = eval(btnSetting);
    var confirmWindow = '';
    
    /**
     * 创建窗口
     */
    if (KXBASE.fn.isNotEmpty(setting.mode) && setting.mode == 'ync') {
        confirmWindow = '<div id="confirmModal" class="confirmModal modal hide fade in" style="width:' + width + 'px; margin-left: ' + (0 - width / 2) + 'px;"><div id="confirmHeader" class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button><h3>' + title + '</h3></div><div class="modal-body noscroll" style="height:' + height + 'px;"><p><img id="confirmImg" src="assets/img/help.png" class="pull-left"/><span id="confirmMsg" class="confirmMsg pull-right">' + msg + '</span></p></div><div id="confirmFooter" class="modal-footer"><a href="#" class="btn btn-primary" id="yesBtn">' + setting.yesBtn + '</a><a href="#" class="btn btn-primary" id="noBtn">' + setting.noBtn + '</a><a href="#" class="btn btn-primary" id="cancelBtn">' + setting.cancelBtn + '</a></div></div>';
    }else if (KXBASE.fn.isNotEmpty(setting.mode) && setting.mode == 'yc'){
        confirmWindow = '<div id="confirmModal" class="confirmModal modal hide fade in" style="width:' + width + 'px; margin-left: ' + (0 - width / 2) + 'px;"><div id="confirmHeader" class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button><h3>' + title + '</h3></div><div class="modal-body noscroll" style="height:' + height + 'px;"><p><img id="confirmImg"  src="assets/img/help.png"  class="pull-left" /><span id="confirmMsg" class="confirmMsg pull-right">' + msg + '</span></p></div><div id="confirmFooter" class="modal-footer"><a href="#" class="btn btn-primary" id="yesBtn">' + setting.yesBtn + '</a><a href="#" class="btn btn-primary" id="cancelBtn">' + setting.cancelBtn + '</a></div></div>';
    }else if (KXBASE.fn.isNotEmpty(setting.mode) && setting.mode == 'close'){
        confirmWindow = '<div id="confirmModal" class="confirmModal modal hide fade in" style="width:' + width + 'px; margin-left: ' + (0 - width / 2) + 'px;"><div id="confirmHeader" class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button><h3>' + title + '</h3></div><div class="modal-body noscroll" style="height:' + height + 'px;"><p><img id="confirmImg"  src="assets/img/info.png"  class="pull-left" /><span id="confirmMsg" class="confirmMsg pull-right">' + msg + '</span></p></div><div id="confirmFooter" class="modal-footer"><a href="#" class="btn btn-primary" id="closeBtn">' + setting.closeBtn + '</a></div></div>';
    }
    $("body").append(confirmWindow);
    /**
     * 绑定按钮事件
     */
    $("#cancelBtn").bind("click", function(){
        $("#confirmModal").modal("hide");
    });
    $("#closeBtn").bind("click", function(){
        $("#confirmModal").modal("hide");
    });
    $("#yesBtn").bind("click", function(){
        yesClick();
    });
    if (KXBASE.fn.isNotEmpty(noClick)) {
    $("#noBtn").bind("click", function(){
        noClick();
    });
    }
    /**
     * 绑定窗口关闭事件
     */
    $("#confirmModal").on("hide",function(){
        $("#closeBtn").unbind("click");
        $("#yesBtn").unbind("click");
        $("#cancelBtn").unbind("click");
        $("#noBtn").unbind("click");
        $("#confirmModal").remove();
        clearTimeout(interval);
    });
    
    /**
     * 显示窗口
     */
    $("#confirmModal").modal({
        backdrop:true,
        keyboard:false
    });
    
    

}
/**
 * 关闭确认框
 * @param {Object} beforeFun 关闭前干什么
 * @param {Object} appendFun 关闭后干什么
 */
function closeConfirmModal(beforeFun,appendFun){
    if(KXBASE.fn.isNotEmpty(beforeFun)){
        beforeFun();
    }
    $("#confirmModal").modal("hide");
    if(KXBASE.fn.isNotEmpty(appendFun)){
        appendFun();
    }
    clearTimeout(interval);
}
/**
 * 确认框出现滚动条
 */
function confirmWaitting(doWhat){
    $("#confirmHeader").hide();
    $("#confirmFooter").hide();
    $("#confirmMsg").html("操作执行中... <br/><img src=\"assets/imgs/waitting.gif\" />");
    if (KXBASE.fn.isNotEmpty(doWhat)) {
        doWhat();
    }
}
/**
 * 确认框显示信息
 */
function confirmShowMsg(msg,sec){
     clearTimeout(interval);
    $("#confirmHeader").hide();
    $("#confirmFooter").hide();
    $("#confirmImg").attr("src","assets/img/info.png");
    $("#confirmMsg").html(msg);
    if(sec>0){
    interval = setInterval(closeConfirmModal, sec); 
    }
}

/***********************************
 * 封装弹出的进度条和弹出的信息框
 *************************************/
//封装弹出loading
function appLoading(msg,time){
   if(msg&&msg.length>0){
   	$("#appLoadingMsg").text(msg);
   }
   	$("#appicon").show();
     $("#appLoading").show();
     if(time&&time>0){
		 setTimeout(function(){
			 $("#appLoading").hide();
		 },time);
     }
 }
//封装弹出loading
function appMsg(msg,time){
   if(msg&&msg.length>0){
   	$("#appLoadingMsg").text(msg);
   }
     $("#appicon").hide();
     $("#appLoading").show();
     if(time&&time>0){
		 setTimeout(function(){
			 $("#appLoading").hide();
		 },time);
     }
 }
//封装弹出loading
function appErrorMsg(msg,time){
	 if(msg&&msg.length>0){
		 $("#appLoadingMsg").html("<span class='t-red font-20'><i class='glyphicon glyphicon-warning-sign pr10'></i>"+msg+"</span>");
	 }
	 $("#appicon").hide();
	 $("#appLoading").show();
	 if(time&&time>0){
		 setTimeout(function(){
			 $("#appLoading").hide();
		 },time);
	 }
}
//封装弹出loading
function appSuccessMsg(msg,time){
   if(msg&&msg.length>0){
   	$("#appLoadingMsg").html("<span class='t-green font-20'><i class='glyphicon glyphicon-ok pr10'></i>"+msg+"</span>");
   }
     $("#appicon").hide();
     $("#appLoading").show();
     if(time&&time>0){
		 setTimeout(function(){
			 $("#appLoading").hide();
		 },time);
     }
 }
function closeAppLoading(){
	 setTimeout(function(){
		 $("#appLoading").hide();
	 },200);
}
 function closeAppLoadingNow(){
     $("#appLoading").hide();
 }
 
function waittingform(form,msg){
	$("#"+form).hide();
	var tempmsg=msg?msg:"正在执行...";
	var div='<div class="appLoading" tabindex="-1" id="appWaitting"><div class="loading-dialog"><div class="loading-msg" >'+tempmsg+'</div>'+
	'<div class="loading-icon" style="height:25px;"></div></div></div>';
	$("#"+form).parent().append(div);
	
}

function closeWaittingForm(form){
	setTimeout(function(){
		$("#"+form).show();
		$("#appWaitting").remove();
		$("#operateBtn",window.parent.document).show();
		$("#extraBtn",window.parent.document).show();
	}, 200);
}

/*********************************************************
 * 各种下拉列表的处理函数
***********************************************************/

/**
 *普通下拉列表的选择处理
 *@param selectedItem              选中的选项object
 *@param selectedValueComponentId  指定的要填写选中项目的值的控件、组件的ID 
 *                                 默认是关联的隐藏域 如果没有默认的可以指定任何一个可以赋值value属性的组件的ID 例如input的ID
 *@param selectedTextComponentId   指定的要填写选中项目的文本的控件、组件的ID
 *                                 此参数关联第二个参数，如果第二个参数不填写或者填写不正确 则此参数无用
 */
KXBASE.fn.dropdownSelectOne=function(selectedItem,selectedValueComponentId,selectedTextComponentId){
    var selectText=selectedItem.text();
    var dropdownhtml=selectText+"<b class='caret'></b>";
    var ulId=selectedItem.parent().parent().attr("id");
    var dropdownId=ulId+"_content";
    $("#"+dropdownId).html(dropdownhtml);
    //如果自己指定了要赋值选中Value的组件
    if(KXBASE.fn.isEmpty(selectedValueComponentId)){
        var hiddenInputId=ulId+"_hidden";
        $("#"+hiddenInputId).val(selectedItem.attr("value"));
    }else{
        $("#"+selectedValueComponentId).val(selectedItem.attr("value"));
        //如果自己指定了要赋值选中的text的组件
        if(KXBASE.fn.isEmpty(selectedValueComponentId)){
            $("#"+selectedTextComponentId).val(selectText);
        }
        }
}




/*********************************************************
 * 框架的主要结构部分 以下是页面加载后主要处理函数区域
***********************************************************/

/**
 * 处理隔行变色 只能框架本身调用
 */
KXBASE.fn.processTableColor=function(){
if($(".tablecolor").length>0){
        $(".tablecolor").each(function(i){
                $(this).find("tr:even").addClass("alt");
        });
    
    }

}
/**
 * 处理滚动panel
 */
KXBASE.fn.processScrollPanel=function(){
if($("div.scrollPanel").length>0){
        $("div.scrollPanel").each(function(){
            $(this).css("height",windowHeight-$(this).offset().top-35).css("overflow-x","hidden").css("overflow-y","auto");
        });

    }
    

}

/**
 * 处理隔行变色 只能框架本身调用
 */
KXBASE.fn.processSubnavListener=function(){
 // fix sub nav on scroll
    var $win = $(window)
      , $nav = $('.subnav')
      , navTop = $('.subnav').length && $('.subnav').offset().top - 40
      , isFixed = 0

    processScroll()

    $win.on('scroll', processScroll)

    function processScroll() {
      var i, scrollTop = $win.scrollTop()
      if (scrollTop >= navTop && !isFixed) {
        isFixed = 1
        $nav.addClass('subnav-fixed')
      } else if (scrollTop <= navTop && isFixed) {
        isFixed = 0
        $nav.removeClass('subnav-fixed')
      }
    }


}



//处理页面弹出提示工具提示信息事件监听
KXBASE.fn.processTooltipListener=function(){
//处理tooltip提示信息
    var pl="top"
if($.browser.msie){
$("[rel='tooltip']").each(function(i){
    pl=$(this).attr("placement");
    $(this).tooltip({
        animation:true,
        placement:pl=='undefined'?'top':pl,
        selector:false,
        trigger:'hover'
        });
});
}else{
    $("[type!='text'][rel='tooltip']").each(function(i){
        pl=$(this).attr("placement");
        $(this).tooltip({
        animation:true,
        placement:pl=='undefined'?'top':pl,
        selector:false,
        trigger:'hover'
        });
    });
}

}


/**
 * 处理下拉选择对话框的事件监听 只能框架本身调用
 */
KXBASE.fn.processDropdownChooseLayerListener=function(){

//处理所有搜索层对话框中的选择按钮 class中带有choose属性的
$(".choose").on("click",function(){
var chooseBtn=$(this);
var pid=$("#searchDialog",window.parent.document).attr("pid");    
$("#"+pid,window.parent.document).val(chooseBtn.attr("choosedText"));
$("#"+pid+"_hidden",window.parent.document).val(chooseBtn.attr("choosedKey"));
var extras=chooseBtn.attr("extras");
if(extras){
    var json=$.parseJSON(extras);
    for(var i in json){
        $("#"+json[i].key,window.parent.document).val(json[i].value);
    }
}
$("#searchframe",window.parent.document).attr("url","");
$("#searchDialog",window.parent.document).hide();
});

//循环所有下拉搜索组件 绑定焦点事件
$(".withSearchDialog").on("focus",function(){
    var input=$(this);
    var pid=input.attr("id");
    var p=input.offset();
    var w=input.attr("dialogWidth");
    if(w=="parent"){
        w=input.width();
    }
    var h=input.attr("dialogHeight");
    var url=input.attr("dialogUrl");
    var ih=30;
    //如果已经弹出了下拉选择搜索组件 就判断是不是自己弹出的
    if($(".searchDialog").length>0){
        //如果是自己弹出的组件 就显示（这里是用在焦点再次停靠的时候）如果不是自己的 就隐藏掉
        if(pid==$("#searchDialog").attr("pid")){
            $("#searchDialog").slideDown();
            return;
        }else{
            $("#searchframe").attr("url","");
            $("#searchDialog").hide();
        }
    }else{//如果在本页面一次都没有弹出过 就创建一个新的弹出层 并且加入到当前文档中
    var searchDialog="<div pid=\""+pid+"\" onmouseover=\"$('#searchDialog').attr('intoFrame','into')\"  onmouseout=\"$('#searchDialog').attr('intoFrame','out')\"  intoFrame=\"out\" id=\"searchDialog\" class=\"searchDialog\" align=\"center\" style=\"display: none; z-index: 999; position: absolute;left:"+p.left+"px;top:"+(p.top+ih)+"px; width:"+w+"px; height:"+h+"px; background: #EEEEEE;  border: 1px solid #dddddd;border-collapse: separate;*border-collapse: collapse;-webkit-border-radius: 4px;-moz-border-radius: 4px;border-radius: 4px; padding: 3px;\">"
                                    +"<a class=\"icon-hand-up pull-left\" style=\"margin-left:5px;\"  href=\"javascript:void(0)\"></a>"
                                    +"<a class=\"icon-remove pull-right\" title=\"关闭\" href=\"javascript:void(0)\" onclick=\"$('#searchDialog').hide();$('#searchframe').attr('url','');\">X</a>"
                                    +"<iframe id=\"searchframe\"  frameborder=\"0\" style=\"width:98%;height:"+(h-ih)+"px;\" src=\"\"></iframe></div>";
    $("body").append(searchDialog);
    }
    //再次将新的值赋给弹出的层
    $("#searchDialog").attr("pid",pid);
    var offset_right=Number(p.left)+Number(w);
    if(offset_right>document.body.clientWidth){
        $("#searchDialog").css("left",self.document.body.clientWidth-w-20);
    }else{
        $("#searchDialog").css("left",p.left);
    }
    $("#searchDialog").css("top",p.top+ih);
    $("#searchDialog").css("width",w);
    $("#searchDialog").css("height",h);
    $("#searchframe").css("height",h-ih);
    $("#searchDialog").slideDown();
    $("#searchframe").attr("src",url);
    
});



        

//绑定焦点移除的
$(".withSearchDialog").on("blur",function(){
            if($("#searchDialog").attr("intoFrame")=="out"){
                $("#searchframe").attr("url","");
                $(".searchDialog").hide();
                }

});

}
/**
 * 处理下拉列表事件监听 只能框架本身调用
 */
KXBASE.fn.processDropdownListener=function(){
$(".dropdown-menu li a").click(function(){
        if($(this).attr("href")=="#"||$(this).attr("href")=="javascript:void(0)"){
            KXBASE.fn.dropdownSelectOne($(this));
        }
    });

}

/**
 * 处理弹出popover事件
 */
KXBASE.fn.processPopoverListener=function(){
    $(".popover-btn").popover();
    $("a[rel=popover]")
    .popover('toggle')
    .bind('click',function(e) {
        e.preventDefault();
        
    })
}


/**
 * 处理分页组件事件监听 只能框架本身调用
 */
KXBASE.fn.processPagerListener=function(){
    var pager=$("#pagination");
    if(KXBASE.fn.isEmpty(pager)||KXBASE.fn.isEmpty(pager.attr("formId"))){
    //alert("没有分页");
    return;
    }
    
    var formId=pager.attr("formId");
    var cp=pager.attr("currentPage");
    var tp=pager.attr("pageTotal");
    var index=0;
    
     //  p: 当前 
     //  pn:总数
    KXBASE.pageNav.fn = function(p,pn){
        if(index>0){
        $("#"+formId).find("#currentPage").val(p);
        $("#"+formId).submit();
        }
        index++;
    };
    KXBASE.pageNav.go(Number(cp),Number(tp));
}


/**
 * 根据权限控制显示和隐藏
 */
KXBASE.fn.processComponents=function(){
    //alert("正在处理页面组件的显示和隐藏");
    //处理隔行变色
    KXBASE.fn.processTableColor();
    KXBASE.fn.processScrollPanel();
}

/**
 * 处理绑定事件
 */
KXBASE.fn.processEventBindings=function(){
    //alert("正在处理页面组件的绑定事件");
    //处理下拉列表
    //KXBASE.fn.processDropdownListener();
    //处理popover
    //KXBASE.fn.processPopoverListener();
    //处理下拉选择弹出对话框事件
    KXBASE.fn.processDropdownChooseLayerListener();
    //处理页面弹出提示工具提示信息事件监听
    //KXBASE.fn.processTooltipListener();
    //处理二级导航
    //KXBASE.fn.processSubnavListener();
    
}
/**
 * 处理select
 */
var selectModal='{{@result}}<option value="{{=_val.optionValue}}">{{=_val.optionText}}</option>{{/@result}}';
KXBASE.fn.processSelect=function(){
    var select= $("select.autoLoad");

    select.each(function(i,obj){
    	if($(obj).attr("firstText")){
    		$(obj).append('<option value="'+$(obj).attr("firstValue")+'">'+$(obj).attr("firstText")+'</option>');
    	}
        var url=$(this).attr("url");
        $.ajax({
            type:"GET",
            url:url,
            dataType:"json",
            context:$(this),
            success:function(result){
                var template = new t(selectModal);
                var html = template.render(result);
                this.append(html);
                this.val(this.attr("selectValue"));
            }
        });
    });
}

/**
 * 页面加载执行事件绑定处理和控制组件根据权限显示和隐藏
 */
$(function(){
    KXBASE.fn.processPagerListener();
    //绑定按钮 下拉列表等组件的事件
    KXBASE.fn.processEventBindings();
    KXBASE.fn.processSelect();
    
    //js校验
    $("form.checkform").on("submit",function(e){
    	waittingform(this.id,"正在验证和提交数据，请稍后...");
        var pass=checkInput($(this));
        if(!pass){
        	closeWaittingForm(this.id);
        }
        return pass;
    });
    
});




var refreshPage=function(){
    if($("form[name='form2']").length>0){
        form2.submit();
    }else{
        window.location.reload();
    }
    
}
var nofun=function(){}


var refreshParentWithForm=function(){
    
        $("#closeModalBtn").bind("click", function(){
                form2.submit();
            });
            $("#closeModalBtnSmall").bind("click", function(){
                form2.submit();
            });
            $(".commonModal").bind("hide", function(){
                form2.submit();
            });
}
var refreshParentWithoutForm=function(){
    
        $("#closeModalBtn").bind("click", function(){
                window.location.reload();
            });
            $("#closeModalBtnSmall").bind("click", function(){
                window.location.reload();
            });
            
            $(".commonModal").bind("hide", function(){
                window.location.reload();
            });
}

var refreshParent=function(){
    if($("form[name='form2']").length>0){
        refreshParentWithForm();
    }else{
        refreshParentWithoutForm();
    }
        
}

var pageBack=function(){
    history.go(-1);
}

var modalBack=function(){
    history.go(-1);
}


